package com.service.impl;

import com.bean.Class;
import com.dao.ClassDao;
import com.dao.impl.ClassDaoImpl;
import com.service.ClassService;
import com.utils.Page;

import java.util.List;

public class ClassServiceImpl implements ClassService {
    ClassDao classDao = new ClassDaoImpl();

    @Override
    public Page<Class> page(int pageNo, int pageSize, String content) {
        Page<Class> page = new Page<>();
        page.setPageSize(pageSize);
        Integer pageTotalCount = classDao.selectForPageTotalCount(content);
        page.setPageTotalCount(pageTotalCount);
        Integer pageTotal = pageTotalCount / pageSize;
        if (pageTotalCount % pageSize > 0) {
            pageTotal += 1;
        }
        page.setPageTotal(pageTotal);
        page.setPageNo(pageNo);
        int begin = (page.getPageNo() - 1) * pageSize;
        List<Class> items = classDao.selectForPageItems(begin, pageSize, content);
        // 设置当前页数据
        page.setItems(items);
        return page;
    }

    @Override
    public Class selectBy(Class aClass) {
        return classDao.selectBy(aClass);
    }

    @Override
    public int deleteById(Integer id) {
        int status = 0;
        if (classDao.deleteByPrimaryKey(id) == -1) {
            status = 1;
        }
        return status;
    }

    @Override
    public int updeteInfo(Class record) {
        int status = 0;
        Class aClass = new Class();
        aClass.setName(record.getName());
        aClass = classDao.selectBy(aClass);
        if (aClass != null && !aClass.getId().equals(record.getId())) {
            status = 1;
        } else if (classDao.updateByPrimaryKey(record) == -1) {
            status = 1;
        }
        return status;
    }

    @Override
    public int insert(Class record) {
        int status = 0;
        Class aClass = new Class();
        aClass.setName(record.getName());
        aClass = classDao.selectBy(aClass);
        System.out.println(aClass);
        if (aClass.getId() != null) {
            status = 1;
        } else if (classDao.insert(record) == -1) {
            status = 1;
        }
        return status;
    }

    @Override
    public List<Class> list() {
        return classDao.selectAll();
    }
}
